
        <div class="ibox float-e-margins" id="account_window">
            <div class="ibox-title" style="border: none;">
                <h5 style="color: #00afef"><i>Add</i></h5>
                <div id="form-add-btn" class="ibox-tools">
                    <i id="loading-icon" style="color: gray; display: none;" class="fa fa-spinner fa-spin fa-lg"></i>&nbsp;
                    <button class="btn btn-sm btn-primary save-btn-tab" id="save_account_btn">Save</button>
                    <button id="cancel_add" class="btn btn-sm btn-primary btn-outline cancel-btn-tab">Cancel</button>
                    <a href="#chglistform_add" class="btn btn-sm btn-info btn-outline save-btn-tab" id="click_list" style="display: none;">Go to Charge List</a>
                </div>
            </div>
            <div class="ibox-content">
                <div style='display: none;' class="spiner-example">
                    <div class="sk-spinner sk-spinner-rotating-plane"></div>
                </div>
                <form class="form-horizontal" id="account_form">
                            <div class="form-group">
                                <label class="col-lg-4 control-label">Entity Name</label>
                                <div class="col-lg-6">
                                    <select name="entity_name" class="form-control m-b entity">
                                    <option value="">---</option>
                                    <?php foreach ($enttys as $key): ?>
                                        <option value="<?php echo $key->entity_id; ?>"><?php echo $key->entity_name; ?></option>
                                    <?php endforeach;?>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-4 control-label">Account Number</label>
                                <div class="">
                                    <div class="input-group">
                                        <div id="noeditable">
                                        </div>
                                        <div id="yeseditable">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-4 control-label">Account Name</label>
                                <div class="col-lg-6">
                                    <input type="text" name="acct_name" class="form-control">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-4 control-label">Account Type</label>
                                <div class="col-lg-6">
                                    <select class="form-control m-b choosen" id="accttype" name="acct_type">
                                        <option value="">Select Type</option>
                                        <?php foreach ($acct_type as $key): ?>
                                        <option value="<?php echo $key->code; ?>"><?php echo $key->meaning; ?></option>
                                        <?php endforeach;?>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-4 control-label">Meter Size</label>
                                <div class="col-lg-6">
                                    <select class="form-control m-b choosen" name="meter_size" id="mtrsize">
                                        <option value="">Select Type</option>
                                        <?php foreach ($meter_size as $key): ?>
                                        <option value="<?php echo $key->lookup_code; ?>"><?php echo $key->meaning; ?></option>
                                        <?php endforeach;?>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-4 control-label">Attention to</label>
                                <div class="col-lg-6">
                                    <input type="text" name="attention_to" class="form-control">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-4 control-label">Account Address</label>
                                <div class="col-lg-6">
                                    <select class="form-control m-b choosen" name="acct_addr">
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-4 control-label">Bill To Address</label>
                                <div class="col-lg-6">
                                    <select class="form-control m-b choosen" name="bill_to_addr">
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-4 control-label">Active Date From</label>
                                <div class="col-lg-6">
                                    <input type="date" name="active_start" class="form-control">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-4 control-label">Active Date To</label>
                                <div class="col-lg-6">
                                    <input type="date" name="active_end" class="form-control">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-4 control-label">Meter Sequence</label>
                                <div class="col-lg-6">
                                    <input type="input" name="meter_seq" class="form-control text-right">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-4 control-label">Location Latitude</label>
                                <div class="col-lg-6">
                                    <input type="text" name="nlat" placeholder="Point your location in the map below" value="0" class="form-control" id="lat" readonly >
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-4 control-label">Location Longitude</label>
                                <div class="col-lg-6">
                                    <input type="text" name="nlng" placeholder="Point your location in the map below" value="0" class="form-control" id="lng" readonly >
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-4 control-label">Pick Location</label>
                                <div class="col-lg-6">
                                    <div id="map_wrapper" style="height: 300px;">
                                        <div id="map_canvas" class="mapping" style="width: 100%;height: 100%;">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-4 control-label">Status</label>
                                <div class="col-lg-6">
                                    <input readonly type="text" value="Pending" class="form-control">
                                    <input type="hidden" name="status" value="PND" class="form-control">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-lg-4 control-label">Enable</label>
                                <div class="col-lg-1">
                                    <input checked type="checkbox" class="i-checks" value="ok" name="ena_flag" >
                                </div>
                            </div>
                        </form>
                            <h4 id="overview" class="page-header">Address Zone <small><i>&#60;this is a read-only section based from the Account Address values.&#62;</i></small></h4>
                <form class="form-horizontal" id="zone_form2">
                             <?php foreach ($zone1 as $key): ?>
                <div class="form-group" style="display: <?php echo ($key->enable_flag == 'N' ? 'none' : ''); ?>">
                        <label class="col-lg-4 control-label"><?php echo $key->field_label; ?></label>
                    <?php endforeach;?>
                                <div class="col-lg-7">
                                    <input readonly type="text" id="z1" class="form-control">
                                </div>
                            </div>
                             <?php foreach ($zone2 as $key): ?>
                <div class="form-group" style="display: <?php echo ($key->enable_flag == 'N' ? 'none' : ''); ?>">
                        <label class="col-lg-4 control-label"><?php echo $key->field_label; ?></label>
                    <?php endforeach;?>
                                <div class="col-lg-7">
                                    <input readonly type="text" id="z2"  class="form-control">
                                </div>
                            </div>
                             <?php foreach ($zone3 as $key): ?>
                <div class="form-group" style="display: <?php echo ($key->enable_flag == 'N' ? 'none' : ''); ?>">
                        <label class="col-lg-4 control-label"><?php echo $key->field_label; ?></label>
                    <?php endforeach;?>
                                <div class="col-lg-7">
                                    <input readonly type="text" id="z3"  class="form-control">
                                </div>
                            </div>
                           <?php foreach ($zone4 as $key): ?>
                <div class="form-group" style="display: <?php echo ($key->enable_flag == 'N' ? 'none' : ''); ?>">
                        <label class="col-lg-4 control-label"><?php echo $key->field_label; ?></label>
                    <?php endforeach;?>
                                <div class="col-lg-7">
                                    <input readonly type="text" id="z4"  class="form-control">
                                </div>
                            </div>
                           <?php foreach ($zone5 as $key): ?>
                <div class="form-group" style="display: <?php echo ($key->enable_flag == 'N' ? 'none' : ''); ?>">
                        <label class="col-lg-4 control-label"><?php echo $key->field_label; ?></label>
                    <?php endforeach;?>
                                <div class="col-lg-7">
                                    <input readonly type="text" id="z5" class="form-control">
                                </div>
                            </div>
                </form>
                            <div id="sub-form" style='display: none;'>
                            <h4 class="page-header">Charge List</h4>
                            <form id="chglist_form_add" class="form-horizontal">
                                <div class="">
                                <table class="table table-bordered" width="100%">
                                    <thead>
                                        <tr>
                                            <th>Charge List</th>
                                            <th>Start Date</th>
                                            <th>End Date</th>
                                            <th>Enable</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tr id="chglistform_add">
                                        <td  style="margin:0px;padding:0px;">
                                            <select style="width:100%;" class="form-control-custom choosen" name="list_id">
                                                <option value="">--</option>
                                                <?php foreach ($chrglist as $key): ?>
                                                <option value="<?php echo $key->list_id; ?>"><?php echo $key->list_name; ?></option>
                                                <?php endforeach;?>
                                            </select>
                                        </td>
                                        <input type="hidden" name="acct_chrg_id">
                                        <td style="margin:0px;padding:0px;"><input style="width:100%;" class="form-control-custom" type="date" name="s_date" value="<?php echo date('Y-m-d'); ?>"></td>
                                        <td style="margin:0px;padding:0px;"><input style="width:100%;" class="form-control-custom" type="date" name="e_date" value="2080-01-01"></td>
                                        <td style="margin:0px;padding:0px;" align="center"><input style="width:100%;" type="checkbox" name="enable_flag" class="i-checks"></td>
                                        <td style="margin:0px;padding:0px;" align="center"><button id="chglist_save_btn_add" type="button" style="width:100%;margin-bottom:0px;" class="btn btn-primary btn-outline add-tab-btn"><i class="fa fa-check fa-fw"></i></button><button style="width: 50%;display:none;margin-bottom:0px;" id="save_edit_chglist_add" type="button" class="add-tab-btn btn btn-primary btn-outline chglist_xtra_btn_add"><i class="fa fa-check fa-fw"></i></button><button style="width: 50%;display:none;margin-bottom:0px;" id="undo_chglist_add" type="button" class="btn btn-danger btn-outline chglist_xtra_btn_add"><i class="fa fa-undo fa-fw"></i></button></td>
                                    </tr>
                                    <tbody id="charglist_tbl_add">
                                    </tbody>
                                </table>
                                </div>
                            </form>
                            <h4 class="page-header"></h4>
                            <h4 id="overview" class="page-header">&nbsp;
                            <button id="add_dev_btn" type="button" class="btn btn-w-m btn-info add-tab-btn">Add Device</button></h4>
                            <div class="ibox-title" style="border: none;">
                                <h5><i>List of Other Device's</i></h5>
                            </div>
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Device ID</th>
                                        <th>Model Nubmer</th>
                                        <th>Serial Number</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody id="table_devices">
                                </tbody>
                            </table>
                    </div>
        </div>
    </div><!-- iBox -->
    <div class="ibox float-e-margins" id="device_window" style='display:none'>
        <div class="ibox-title" style="border: none;">
                <h5 style="color: #00afef"><i>Add Device</i></h5>
                <div id="form-add-btn" class="ibox-tools">
                    <button class="btn btn-sm btn-primary save-btn-tab" id="ins_dev_btn">Save</button>
                    <button class="btn btn-sm btn-primary btn-outline cancel-btn-tab" id="ins_dev_close_btn">Close</button>
                </div>
            </div>
        <div class="ibox-content">
                 <form class="form-horizontal" id="device_form">
                    <div class="form-group">
                        <label class="col-lg-4 control-label">Item Number</label>
                        <div class="col-lg-7">
                            <select class="form-control m-b choosen" name="item_num">
                                <option value="">Select Item Number</option>
                                <?php foreach ($item as $i): ?>
                                <option value="<?php echo $i->item_id; ?>"><?php echo $i->item_num; ?></option>
                                <?php endforeach;?>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-4 control-label">Device Type</label>
                        <div class="col-lg-7">
                            <select class="form-control m-b choosen" name="dev_type">
                                <option value="">Select Device Type</option>
                                <?php foreach ($devtype as $dt): ?>
                                <option value="<?php echo $dt->type; ?>"><?php echo $dt->meaning; ?></option>
                                <?php endforeach;?>
                            </select>
                        </div>
                    </div>
                     <div class="form-group">
                        <label class="col-lg-4 control-label">Model Number</label>
                        <div class="col-lg-7">
                            <input type="text" name="model_number" class="form-control">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-4 control-label">Serial Number</label>
                        <div class="col-lg-7">
                            <input type="text" name="serial_number" class="form-control">
                        </div>
                    </div>
                     <div class="form-group">
                        <label class="col-lg-4 control-label">Device ID</label>
                        <div class="col-lg-7">
                            <input   type="text" name="dev_id" class="form-control">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-4 control-label">Installation Date</label>
                        <div class="col-lg-7">
                            <input type="text" name="install_date" class="form-control">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-4 control-label">Warranty Period</label>
                        <div class="col-lg-7">
                            <input type="text" name="warranty_per" class="form-control">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-4 control-label">Initial Reading</label>
                        <div class="col-lg-7">
                            <input type="text" name="initial_read" class="form-control">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-4 control-label">Last Reading</label>
                        <div class="col-lg-7">
                            <input type="text" name="last_read" class="form-control">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-4 control-label">Status</label>
                        <div class="col-lg-7">
                            <select class="form-control m-b choosen" name="status">
                                <option value="">Select Status</option>
                                <?php foreach ($devstats as $ds): ?>
                                <option value="<?php echo $ds->status; ?>"><?php echo $ds->meaning; ?></option>
                                <?php endforeach;?>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-4 control-label">Device Remarks</label>
                        <div class="col-lg-7">
                            <input type="text" name="dev_remarks" class="form-control">
                        </div>
                    </div>
                </form>
        </div>
    </div>

    <script type="text/javascript">
            $(document).ready(function() {
                getflexseqs2();
                var intervalId = window.setInterval(function(){
                  getflexseqs();
                }, 1500);
                function getflexseqs(){
                    $.ajax({
                        url: "<?php echo base_url('sys/flex_seqs/get_flex_seqs'); ?>",
                        method:'POST',
                        dataType:'json',
                        data: $('#account_form').serialize()+'&'+$.param({'table_name' : 'ar_account', 'table_field' : 'acct_num'}),
                        success: function (data) {
                            var tmp_y = '';
                            var tmp_n = '';
                            $.each(data,function(i,item) {
                                //console.log(data[i].editable_flag);
                                if(data[i].editable_flag == 'Y'){
                                    //$("#"+data[i].seg_name+"_fx").val(data[i].value);
                                }else{ 
                                    $("#"+data[i].seg_name+"_fx").val(data[i].value);
                                }
                            }); 
                        }
                    });
                }

                function getflexseqs2(){
                    $.ajax({
                        url: "<?php echo base_url('sys/flex_seqs/get_flex_seqs_2'); ?>",
                        method:'POST',
                        dataType:'json',
                        data: $('#account_form').serialize()+'&'+$.param({'table_name' : 'ar_account', 'table_field' : 'acct_num'}),
                        success: function (data) {
                            var tmp_y = '';
                            var tmp_n = '';
                            $.each(data,function(i,item) {
                                //console.log(data[i].editable_flag);
                                if(data[i].editable_flag == 'Y'){
                                    tmp_y += '<div class="col-lg-'+(parseFloat(data[i].seg_length) + 1)+'"><input type="text" maxlength="'+data[i].seg_length+'" id="'+data[i].seg_name+'_fx" value="'+data[i].value+'" class="form-control text-right"/></div>';
                                }else{ 
                                    tmp_n += '<div class="col-lg-'+(parseFloat(data[i].seg_length) + 1)+'"><input type="text" readonly maxlength="'+data[i].seg_length+'" id="'+data[i].seg_name+'_fx" '+(data[i].value != '' ? "value='"+data[i].value+ "' " : '')+' class="form-control text-right"/></div>';
                                }
                            }); 
                            $('#yeseditable').html(tmp_y);
                            $('#noeditable').html(tmp_n);
                        }
                    });
                }

                function concat_flex(){
                    var concat = '';
                    $.ajax({
                        url: "<?php echo base_url('sys/flex_seqs/get_flex_seqs_2'); ?>",
                        method:'POST',
                        dataType:'json',
                        async: false,
                        data: $('#account_form').serialize()+'&'+$.param({'table_name' : 'ar_account', 'table_field' : 'acct_num'}),
                        success: function (data) {
                            var count = 0;
                            $.each(data,function(i,item) {
                                if(data[i].editable_flag == 'Y'){
                                     concat += $("#"+data[i].seg_name+"_fx").val();
                                }else{ 
                                    concat += data[i].value;
                                }
                                if(count != (data.length - 1)){
                                    concat += data[i].separator;
                                }
                                count++;
                            });
                        }
                    });
                    return concat;
                }

                //-----------------
                $('.entity').chosen({width: '100%'});
                $('.choosen').chosen({width: '100%'});
                //create_work_order();

                $('#account_form #accttype').change(function(){
                    $('#account_form #account_typeee').text($(this).val());
                });

                $('#account_form #mtrsize').change(function(){
                    $('#account_form #meter_sizeee').text($(this).val());
                });
                var markers =[];
                initialize();

        function initialize() {
           var mapProp = {
            center:new google.maps.LatLng(8.347557925845486,124.27363961935043),
            zoom:17,
            mapTypeId:google.maps.MapTypeId.SATELITE
          };
          var map=new google.maps.Map(document.getElementById("map_canvas"),mapProp);
            google.maps.event.addDomListener(window, 'load', initialize);

          map.addListener('click', function(e) {
            placeMarkerAndPanTo(e.latLng, map);
          });  
        // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
        }


        function placeMarkerAndPanTo(latLng, map) {
          DeleteMarkers();
          var marker = new google.maps.Marker({
            position: latLng,
            map: map
          });
          map.panTo(latLng);

          markers.push(marker);
          $('#lat').val(latLng.lat());
          $('#lng').val(latLng.lng());

        }


        function DeleteMarkers() {
        //Loop through all the markers and remove
            for (var i = 0; i < markers.length; i++) {
                markers[i].setMap(null);
            }
            markers = [];
        }




                $('#add_dev_modal_body').slimScroll({
                    height: '500px',
                    railVisible: true
                });
                $('#add_acc_modal_body').slimScroll({
                    height: '500px',
                    railVisible: true
                });

                 $('#add_addr_modal_body').slimScroll({
                    height: '500px',
                    railVisible: true
                });
                $('#entity_form .form-group.person').hide();

                sessionStorage.acct_entity_id = '';
                sessionStorage.account_id2 = '';

                $('.i-checks').iCheck({
                    checkboxClass: 'icheckbox_square-green',
                    radioClass: 'iradio_square-green'
                });

                $('#account_form select[name=entity_name]').change(function(){
                    var id = $(this).val();
                    sessionStorage.acct_entity_id = id;
                    $.ajax({
                            url: "<?php echo base_url($this->session->userdata('forajax') . '/get_entities'); ?>",
                            method:'post',
                            data: { 'entity_id': id },
                            dataType:'json',
                            success: function (data) {
                                console.log(data);
                                var tmp = '';
                                var num = 1;
                                var igit = '';
                                $.each(data, function(i,items){
                                    igit = '';
                                    if(num == 1){
                                        igit = 'selected';
                                        $('#account_form select[name=acct_addr]').val('"'+data[i].address_id+'"').trigger('change');
                                        num++;
                                    }
                                   $('#account_form input[name=entity_name]').val(data[i].entity_name);
                                   $('#account_form input[name=acct_name]').val(data[i].entity_name);
                                   tmp += "<option value='"+data[i].address_id+"' '"+igit+">"+data[i].addr_code+"</option>";
                                });
                                $('#account_form select[name=acct_addr]').html(tmp);
                                $('#account_form select[name=bill_to_addr]').html(tmp);
                                $(".choosen").trigger("chosen:updated");
                                zonedaw();
                            },
                            complete: function() {
                                $('.spiner-example').hide();
                                $('#zone_form2').show();
                                $('#account_form').show();
                            },
                            beforeSend: function(){
                                $('#account_form').hide();
                                $('#zone_form2').hide();
                                $('.spiner-example').show();
                            }
                        });
                });

                $('select[name=entity_type]').change(function(){
                    if($(this).val() == "ORG"){
                        $('#entity_form .form-group.organization').show();
                        $('#entity_form .form-group.person').hide();
                    }else{
                        $('#entity_form .form-group.person').show();
                        $('#entity_form .form-group.organization').hide();
                    }
                });

                function getchglistadd(){
                $('#charglist_tbl_add').html('');
                    $.ajax({
                        url: '<?php echo base_url($this->session->userdata("forajax")); ?>/get_chglist',
                        method: 'POST',
                        data: { 'account_id': sessionStorage.account_id2 },
                        dataType: 'json',
                        success: function(data){
                            console.log(data.length);
                            if(data.length !== 0){
                                $('#chglistform_add').hide();
                                var tmp = '';
                                var state = '';
                                $.each(data, function(i,item){
                                    if(data[i].enable_flag == 'Y'){
                                        state = 'checked';
                                    }
                                    tmp += "<tr id='rmv_chglist_add'><td style='display:none;' id='acct_chrg_id_v'>"+ data[i].acct_chrglst_id +"</td><td style='display:none;' id='enable_flag_v'>"+ data[i].enable_flag +"</td><td style='display:none;' id='list_id_v'>"+ data[i].list_id +"</td><td style='margin:0px;padding:0px;vertical-align: middle;' id='list_name_v'>"+ data[i].list_name +"</td><td align='right' style='margin:0px;padding:0px;vertical-align: middle;' id='start_date_v'>"+ data[i].start_date +"</td><td align='right' style='margin:0px;padding:0px;vertical-align: middle;' id='end_date_v'>"+ data[i].end_date +"</td><td align='center' style='margin:0px;padding:0px;vertical-align: middle;'><input disabled type='checkbox' "+state+" class='i-checks'></td><td style='margin:0px;padding:0px;vertical-align: middle;' class='add_btn_group' ><button id='chglist_edit_btn_add' style='margin-bottom: 0px;' type='button' class='btn btn-primary btn-outline btn-block'><i class='fa fa-pencil fa-fw'></i></button></td></tr>";
                                    //$('.chg-list option[value='+data[i].list_id +']').remove();
                                });
                                $('#charglist_tbl_add').html(tmp);
                                //getchglistadd2();
                            }else{
                                $('#chglistform_add').show();
                            }
                            $(".chg-list").trigger("chosen:updated");
                            $('input').iCheck('update');
                        }
                    });
                }

                $(document).on('click','#chglist_edit_btn_add',function(){
                    if(sessionStorage.chglistbtncount1 == '0'){
                        var listid = $(this).closest('tr').children('#list_id_v').text();
                        var listname = $(this).closest('tr').children('#list_name_v').text();
                        var startdate = $(this).closest('tr').children('#start_date_v').text();
                        var enddate = $(this).closest('tr').children('#end_date_v').text();
                        var enable_flag = $(this).closest('tr').children('#enable_flag_v').text();
                        var id = $(this).closest('tr').children('#acct_chrg_id_v').text();
                        console.log(listid);
                        $('#chglist_form_add input[name=acct_chrg_id]').val(id);
                        $('#chglist_form_add select[name=list_id]').val(listid);
                        $('#chglist_form_add input[name=s_date]').val(startdate);
                        $('#chglist_form_add input[name=e_date]').val(enddate);
                        if(enable_flag == 'Y'){
                            $('#chglist_form_add input[name=enable_flag]').attr('checked', true);
                        }else{
                            $('#chglist_form_add input[name=enable_flag]').removeAttr('checked');
                        }
                        $(this).closest('tr').children('.add_btn_group').html("<a style='width: 50%;' id='edit_chrglist_btn' type='button' class='btn btn-primary btn-outline'><i class='fa fa-check fa-fw'></i></a><a id='undo_chglist_add' style='width: 50%;' type='button' class='btn btn-danger btn-outline'><i class='fa fa-undo fa-fw'></i></a>");
                        sessionStorage.chglistbtncount1 = '1';
                        $('#rmv_chglist_add').hide();
                        $('.chglist_xtra_btn_add').show();
                        $('#chglistform_add').show();
                        $('#chglist_save_btn_add').hide();
                        $(".chg-list").trigger("chosen:updated");
                        $('input').iCheck('update');
                    }
                });

                $(document).on('click','#undo_chglist_add',function(){
                    sessionStorage.chglistbtncount1 = '0';
                    getchglistadd();
                    $('.chglist_xtra_btn_add').hide();
                    $('#chglistform_add').hide();
                    $('#chglist_save_btn_add').show();
                });

                $(document).on('click','#save_edit_chglist_add',function(){
                    if($('#chglist_form_add').valid() == false){
                         notifymsg('danger','Please Fill Charge list');
                     }else{
                        $.ajax({
                            url: '<?php echo base_url($this->session->userdata("forajax")); ?>/upd_chrglist',
                            method: 'POST',
                            data: $('#chglist_form_add').serialize()+'&'+$.param({ 'account_id': sessionStorage.account_id2 }),
                            dataType: 'json',
                            success: function(data){
                                if(data.err == 1){
                                    notifymsg('danger','<b>Error</b>: '+data.msg);
                                }else{
                                    notifymsg('success','<b>Success</b>: Data saved.');
                                    sessionStorage.chglistbtncount1 = '0';
                                    getchglistadd();
                                    $('.chglist_xtra_btn_add').hide();
                                    $('#chglistform_add').hide();
                                    $('#chglist_save_btn_add').show();
                                }
                            }
                        });
                    }
                });

                $('#chglist_save_btn_add').click(function(){
                    if(sessionStorage.account_id2 == '' || sessionStorage.account_id2 == undefined){
                        notifymsg('danger','Please add an Account first'); // notifytoast(type, title, msg)
                    }else{
                        if($('#chglist_form_add').valid() == false){
                             notifymsg('danger','Please Fill Charge list');
                        }else{
                            $.ajax({
                                url: '<?php echo base_url($this->session->userdata("forajax")) . "/add_chglist" ?>',
                                method: 'POST',
                                data: $('#chglist_form_add').serialize()+'&'+$.param({ 'account_id': sessionStorage.account_id2 }),
                                dataType: 'json',
                                success: function(data){
                                    if(data.err == 1){
                                        notifymsg('danger','<b>Error</b>: '+data.msg);
                                        //notifytoast('error','Error',data.msg);
                                    }else{
                                        notifymsg('success','<b>Success</b>: Data saved.');
                                        $('#cancel_add').show();
                                        $('#cancel_add').html('Close');
                                        $('#click_list').hide();
                                        //notifytoast('success','Success', 'Data saved');
                                        getchglistadd();
                                        $('#chglist_save_btn_add').hide();
                                    }
                                }
                            });
                        }
                    }
                });

                $('#chglist_form_add').validate({
                    rules: {
                        list_id: {
                            required: true
                        }
                    }
                });

                $("#entity_form").validate({
                     rules: {
                         entity_name: {
                            required: true
                         },
                         first_name: {
                            required : true
                         },
                         last_name: {
                            required: true
                         },
                         tax_reg_num: {
                            required: true,
                            number: true
                         }
                     }
                });
                $("#entity_address_form").validate({
                     rules: {
                         addr_1: {
                            required: true
                         },
                         country: {
                            required: true
                         },
                         city_town: {
                            required: true
                         },
                         postal_code: {
                            required: true
                         }
                     }
                });
                $.validator.setDefaults({ ignore: ":hidden:not(select)" })
                 $("#entity_address_form_2").validate({
                     rules: {
                         addr_code: {
                            required: true
                         },
                         addr_1: {
                            required: true
                         },
                         country: {
                            required: true
                         },
                         city_town: {
                            required: true
                         },
                         postal_code: {
                            required: true
                         }
                     }
                });

                 $("#device_form").validate({
                     rules: {
                         item_num: {
                            required: true
                         },
                         dev_type: {
                            required: true
                         },
                         model_number: {
                            required: true
                         },
                         serial_number: {
                            required: true
                         }
                     }
                });
                $('#save_entity').click(function(){
                    if($("#entity_form").valid() == true && $("#entity_address_form").valid() == true){
                        $.ajax({
                            url: "<?php echo base_url($this->session->userdata('forajax') . '/insert'); ?>",
                            method:'post',
                            data:$('#entity_form').serialize(),
                            dataType:'json',
                            success: function (data) {
                                if(data.err == 1){
                                   notifymsg('danger','<b>Error</b>: '+data.msg);
                                }else{
                                    notifymsg('success','<b>Success</b>: Data saved.');
                                    sessionStorage.acct_entity_id = data.id;
                                    $("#entity_form").find(':input:not(:disabled)').prop('disabled',true);
                                    inserAddr($("#entity_address_form").serialize(),data.id);
                                    $('#save_entity').removeAttr('id');
                                }
                            },
                            complete: function() {
                                $("#save_entity").removeAttr("disabled");
                                $('#loading-icon').hide();
                            },
                            beforeSend: function(){
                                $("#save_entity").attr("disabled", true);
                                $('#loading-icon').show();
                            }
                        });
                    }
                });
                $('#save_address_btn').click(function(){
                    if($("#entity_address_form_2").valid() == true){
                        inserAddr($("#entity_address_form_2").serialize(),sessionStorage.acct_entity_id);
                    }
                });

                function zonedaw(){
                     $.ajax({
                        url: "<?php echo base_url($this->session->userdata('forajax') . '/get_zones'); ?>",
                        method:'post',
                        data: { 'entity_id': sessionStorage.acct_entity_id, 'addr_code':  $('#account_form select[name=acct_addr]').val()},
                        dataType:'json',
                        success: function (data) {
                               $('#zone_form2 #z1').val(data[0].zone_1);$('#zone_form2 #z2').val(data[0].zone_2);
                               $('#zone_form2 #z3').val(data[0].zone_3);$('#zone_form2 #z4').val(data[0].zone_4);
                               $('#zone_form2 #z5').val(data[0].zone_5);
                               $('#account_form #zone_1ee').text(data[0].zone_1);
                               $('#account_form #zone_2ee').text(data[0].zone_2);
                        }
                    });
                }

                $('#account_form select[name=acct_addr]').change(function(){
                    console.log($(this).val());
                    var addrcode = $(this).val();
                    $.ajax({
                        url: "<?php echo base_url($this->session->userdata('forajax') . '/get_zones'); ?>",
                        method:'post',
                        data: { 'entity_id': sessionStorage.acct_entity_id, 'addr_code': addrcode},
                        dataType:'json',
                        success: function (data) {
                               $('#zone_form2 #z1').val(data[0].zone_1);$('#zone_form2 #z2').val(data[0].zone_2);
                               $('#zone_form2 #z3').val(data[0].zone_3);$('#zone_form2 #z4').val(data[0].zone_4);
                               $('#zone_form2 #z5').val(data[0].zone_5);
                               $('#account_form #zone_1ee').text(data[0].zone_1);
                               $('#account_form #zone_2ee').text(data[0].zone_2);
                        }
                    });
                });
                $('#add_acc_btn').click(function(){
                    $('#table_devices').html('');
                    if(typeof(sessionStorage.acct_entity_id) == 'undefined' || sessionStorage.acct_entity_id == ''){
                        notifymsg('danger','<b>Error:</b> Please Add an Entity and Address First.');
                    }else{
                        $('#account').modal('show');
                        $("#account_form")[0].reset();
                        $("#account_form").find(':input(:disabled)').removeAttr('disabled');
                        $('#save_account_btn').removeAttr("disabled");
                        $.ajax({
                            url: "<?php echo base_url($this->session->userdata('forajax') . '/get_entities'); ?>",
                            method:'post',
                            data: { 'entity_id': sessionStorage.acct_entity_id },
                            dataType:'json',
                            success: function (data) {
                                console.log(data);
                                var tmp = '';
                                $.each(data, function(i,items){
                                   $('#account_form input[name=entity_name]').val(data[i].entity_name);
                                   tmp += "<option value='"+data[i].address_id+"''>"+data[i].addr_code+"</option>";
                                });
                                $('#account_form select[name=acct_addr]').html(tmp);
                                $('#account_form select[name=bill_to_addr]').html(tmp);

                            },
                            complete: function() {
                                $('.spiner-example').hide();
                                $('#zone_form2').show();
                                $('#account_form').show();
                            },
                            beforeSend: function(){
                                $('#account_form').hide();
                                $('#zone_form2').hide();
                                $('.spiner-example').show();
                            }
                        });
                    }
                });

                $("#account_form").validate({
                     rules: {
                         entity_name: {
                            required: true
                         },
                         acct_type: {
                            required : true
                         },
                         acct_name: {
                            required: true
                         },
                         meter_size: {
                            required: true
                         }
                     }
                });

                $('#save_account_btn').click(function(){
                    if($("#account_form").valid() == true){
                        var acct_num1 = $('#account_form #zone_1ee').text() + $('#account_form #zone_2ee').text() + '-' + $('#account_form #account_typeee').text() + $('#account_form #meter_sizeee').text() + '-' + $('#account_form #acctnum').val();
                        var acct_num = concat_flex();
                        $.ajax({
                            url: "<?php echo base_url($this->session->userdata('forajax') . '/insert_acc'); ?>",
                            method:'post',
                            data: $('#account_form').serialize()+'&'+$.param({ 'entity_id': sessionStorage.acct_entity_id,'acct_num': acct_num }),
                            dataType:'json',
                            success: function (data) {
                                if(data.err == 1){
                                   notifymsg('danger','<b>Error</b>: '+data.msg);
                                   $('#save_account_btn').removeAttr('disabled');
                                }else{
                                    window.clearInterval(intervalId);
                                    notifymsg('success','<b>Success</b>: Data saved.');
                                    sessionStorage.account_id2 = data.id;
                                    getAccounts();
                                    create_work_order(data.id);
                                    //$("#account_form").find('select :input:not(:disabled)').prop('disabled',true);
                                    //$('#account_form').find('input, textarea, button, select').attr('disabled','disabled');
                                    $("select").trigger("chosen:updated");
                                    $('#save_account_btn').prop('disabled',true);
                                    $('#save_account_btn').hide();
                                    $('#cancel_add').hide();
                                    $('#click_list').show();
                                    $('#chglist_form_add').removeAttr('disabled');
                                    $('#sub-form').show();
                                    //$('#account_form input[name=acct_num]').val(data.accnum);
                                    $('#click_list').trigger('click');
                                }
                            },
                            complete: function() {
                                $('#loading-icon-acc').hide();
                            },
                            beforeSend: function(){
                                $('#loading-icon-acc').show();
                                $('#save_account_btn').attr('disabled',true);
                            }
                        });
                    }
                });

                function  create_work_order(cus_id){
                    var someDate = new Date();
                    var numberOfDaysToAdd = 6;
                    someDate.setDate(someDate.getDate() + numberOfDaysToAdd); 

                    var dd = someDate.getDate();
                    var mm = someDate.getMonth() + 1;
                    var y = someDate.getFullYear();

                    var someFormattedDate = y + '-'+ mm + '-'+ dd;
                    //console.log(someFormattedDate);
                    $.ajax({
                            url: "<?php echo base_url($this->session->userdata('forajax') . '/create_wo'); ?>",
                            method:'post',
                            data: {"acct_id":cus_id, "target_date" : someFormattedDate},
                            dataType:'json',
                            success: function (data) {
                                if(data.err == 1){
                                   notifymsg('danger','<b>Error</b>: '+data.msg);
                                   
                                }else{
                                    
                                }
                            },
                            complete: function() {
                            
                            },
                            beforeSend: function(){
                       
                            }
                        });

                    
                }

                 $('#ins_dev_btn').click(function(){
                    if( $("#device_form").valid() == true){
                        $.ajax({
                            url: "<?php echo base_url($this->session->userdata('forajax') . '/insert_dev'); ?>",
                            method:'post',
                            data: $('#device_form').serialize()+'&'+$.param({ 'account_id': sessionStorage.account_id2 }),
                            dataType:'json',
                            success: function (data) {
                                if(data.err == 1){
                                   notifymsg('danger','<b>Error</b>: '+data.msg);
                                }else{
                                    notifymsg('success','<b>Success</b>: Data saved.');
                                    getDevice(sessionStorage.account_id2);
                                    $('#account_window').show();
                                    $('#device_window').slideUp();
                                }
                            },
                            complete: function() {
                                $('#loading-icon-dev').hide();
                            },
                            beforeSend: function(){
                                $('#loading-icon-dev').show();
                            }
                        });
                    }
                });

                function getDevice(acct_id){
                    $.ajax({
                        url: "<?php echo base_url($this->session->userdata('forajax') . '/get_device'); ?>",
                        method:'post',
                        data: {'account_id': acct_id},
                        dataType:'json',
                        success: function (data) {
                            var tmp = ''
                            var count = 1;
                            $.each(data, function(i, item) {
                                 tmp += "<tr><td>"+count+"</td><td style='display:none;' id='dev_id_edit'>"+data[i].device_assignment_id+"</td><td>"+data[i].device_id+"</td><td>"+data[i].model_number+"</td><td>"+data[i].serial_number+"</td><td>"+data[i].dev_stat_meaning+"</td><tr>";
                                 count++;
                            });
                            $('#table_devices').html(tmp);
                        }
                    });
                }

                $('#add_dev_btn').click(function() {
                    if(typeof(sessionStorage.account_id2) == 'undefined' || sessionStorage.account_id2 == ''){
                        notifymsg('danger','<b>Error:</b> Please Add an Account First.');
                    }else{
                        $("#device_form")[0].reset();
                        $("#device_form .choosen").val('').trigger("chosen:updated");
                        notifymsg('hide','hide');
                        $('#account_window').hide();
                        // $('#device_window').show();
                        $('#device_window').slideDown();
                    }
                });
                $('#ins_dev_close_btn').click(function(){
                    $('#account_window').slideDown();
                    $('#device_window').slideUp();
                });

                function inserAddr(forms,id) {
                    $.ajax({
                        url: "<?php echo base_url($this->session->userdata('forajax') . '/insert_addr'); ?>",
                        method:'post',
                        data: forms+'&'+$.param({ 'entity_id': id }),
                        dataType:'json',
                        success: function (data) {
                            if(data.err == 1){
                                notifymsg('danger','<b>Error</b>: '+data.msg);
                            }else{
                                notifymsg('success','<b>Success</b>: Data saved.');
                                $('#addresses').modal('hide');
                                getAddress(id);
                                if(forms == $("#entity_address_form_2").serialize()){
                                    $("#entity_address_form_2")[0].reset();
                                }else{
                                    $("#entity_address_form :input").prop('disabled', true);
                                }
                            }
                        },
                        complete: function() {
                            $('#loading-icon-addr').hide();
                            //$("#save_entity").removeAttr("disabled");
                        },
                        beforeSend: function(){
                            $('#loading-icon-addr').show();
                            //$("#save_entity").attr("disabled", true);
                        }
                    });
                }

                function getAddress(id){
                    $.ajax({
                        url: "<?php echo base_url($this->session->userdata('forajax') . '/getAddress2'); ?>",
                        method:'post',
                        data: { 'entity_id': id },
                        dataType:'json',
                        success: function (data) {
                            var tmp = '';
                            var count = 1;
                            var enable = "";
                            $.each(data, function(i, item) {
                                if(data[i].enable_flag == 'Y'){
                                    enable = "checked";
                                }
                                if(data[i].addr_code !== 'MAIN'){
                                    tmp += "<tr><td>"+count+"</td><td>"+data[i].address_1+"</td><td>"+data[i].addr_code+"</td><td align='center'><div class='state icheckbox_square-green "+ enable +"'></div></td></tr>"
                                    count++;
                                }
                            });
                            $('#table_address').html(tmp);
                        }
                    });
                }

                function getAccounts(){
                    $.ajax({
                        url: "<?php echo base_url($this->session->userdata('forajax') . '/getAccount2'); ?>",
                        method:'post',
                        data: { 'entity_id': sessionStorage.acct_entity_id },
                        dataType:'json',
                        success: function (data) {
                            var tmp = '';
                            var count = 1;
                            var enable = "";
                            $.each(data, function(i, item) {
                                if(data[i].enable_flag == 'Y'){
                                    enable = "checked";
                                }
                                tmp += "<tr><td>"+count+"</td><td>"+data[i].acct_name+"</td><td>"+data[i].acct_type+"</td><td align='center'><div class='state icheckbox_square-green "+ enable +"'></div></td><td>"+data[i].status_meaning+"</td></tr>"
                                count++;
                            });
                            $('#table_accounts').html(tmp);
                        }
                    });
                }
                $('#account_form').data('serialize',$('#account_form').serialize());
                
                $(function(){
                   $.ajax({
                        url: "<?php echo base_url($this->session->userdata('forajax') . '/getMeterSeq'); ?>",
                        method:'get',
                        dataType:'json',
                        success: function (data) {
                            $.each(data,function(i,item) {
                                 $('#account_form input[name=meter_seq]').val(data[i].meter_seq);
                            });    
                        }
                    });
                });



                function alert_cancel(){
                    if($('#account_form').serialize()!=$('#account_form').data('serialize')){
                        // Form has changed!!!
                        swal({
                          title: "Are you sure?",
                          text: "Your work will not be save",
                          type: "warning",
                          showCancelButton: true,
                          confirmButtonColor: "#DD6B55",
                          confirmButtonText: "Leave",
                          cancelButtonText: "Stay",
                          closeOnConfirm: true,
                          closeOnCancel: true },
                      function (isConfirm) {
                          if (isConfirm) {
                            swal("success");
                              close_add(); active_search();
                              notifyClass("clear","");
                          } else {
                              swal("Cancelled");
                          }
                      });
                        }else{
                            close_add(); active_search();
                            notifymsg("hide","hide");
                        }
                    }

                $('#cancel_add').click(function(){
                    alert_cancel();
                });

                $('#addX').click(function(){
                    alert_cancel();
                });

                 $(document).on({
                    'show.bs.modal': function () {
                        var zIndex = 1040 + (10 * $('.modal:visible').length);
                        $(this).css('z-index', zIndex);
                        setTimeout(function() {
                            $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
                        }, 0);
                    },
                    'hidden.bs.modal': function() {
                        if ($('.modal:visible').length > 0) {
                            // restore the modal-open class to the body element, so that scrolling works
                            // properly after de-stacking a modal.
                            setTimeout(function() {
                                $(document.body).addClass('modal-open');
                            }, 0);
                        }
                    }
                }, '.modal');

            });

    </script>